package com.kestrel.space.common.controller;

import io.jsonwebtoken.Claims;
import com.alibaba.fastjson.JSONObject;
import com.kestrel.space.common.model.User;
import com.kestrel.space.common.utils.BizException;
import com.kestrel.space.common.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author yebolin
 * @date 2024/8/21
 */
public class BaseController {
    private static final String DEFAULT_ENCODING = "UTF-8";

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public BaseController() {
    }

    protected User getUser() throws Exception {
        return getCurrentUser(this.request);
    }

    public User getCurrentUser(HttpServletRequest req) throws Exception {
        User user = null;
        if (req == null) {
            user = new User();
            user.setUsername("游客");
        } else {
            String token = req.getHeader("token");
            Claims jwt = JwtUtil.parseJWT(token);
            user = JSONObject.parseObject(jwt.getSubject(), User.class);
            if (user == null) {
                user = new User();
                user.setUsername("游客");
            }
        }
        return user;
    }
}
